﻿using UnityEngine;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Rendering;
using Jinndev.ECS;

namespace Jinndev.Rendering2D {

    /// <summary>
    /// 通过CullingSystem实现，用于为带有RenderMesh的实体设置DisableRendering<br/>
    /// 需要组件：Culling, [RenderMesh, CustomRenderer]中任意一个<br/>
    /// 结果：添加/移除DisableRendering
    /// </summary>
    [UpdateAfter(typeof(CullingSystem.ECB))]
    public class CustomCullingSystem : JobComponentSystem {

        private EntityQuery becomeInvisibleQuery;
        private EntityQuery becomeVisibleQuery;

        protected override void OnCreate() {
            becomeInvisibleQuery = GetEntityQuery(new EntityQueryDesc {
                All = new ComponentType[] {
                    ComponentType.ReadOnly<RenderMesh>(),
                    ComponentType.ReadOnly<Culling>(),
                    ComponentType.ReadOnly<Culled>()
                },
                None = new ComponentType[] {
                    ComponentType.ReadOnly<DisableRendering>()
                }
            });

            becomeVisibleQuery = GetEntityQuery(new EntityQueryDesc {
                All = new ComponentType[] {
                    ComponentType.ReadOnly<RenderMesh>(),
                    ComponentType.ReadOnly<Culling>(),
                    ComponentType.ReadOnly<DisableRendering>()
                },
                None = new ComponentType[] {
                    ComponentType.ReadOnly<Culled>()
                }
            });
        }

        protected override JobHandle OnUpdate(JobHandle inputDeps) {
            // 从可见变不可见
            EntityManager.AddComponent<DisableRendering>(becomeInvisibleQuery);
            //// 从不可见变可见
            EntityManager.RemoveComponent<DisableRendering>(becomeVisibleQuery);
            return inputDeps;
        }

    }

}

